﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using DeansWsccProject.App_Code;

namespace DeansWsccProject
{
    public partial class profile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["profileUserName"] == null) // If no username present in querystring, do one of the following...
            {
                if (User.Identity.IsAuthenticated)
                {
                    Response.Redirect("~/profile.aspx?profileUserName=" + User.Identity.Name); // Navigate to user's own profile by appending username querystring if they're logged in
                }
                else
                {
                    Response.Redirect("~/authors-list.aspx"); // Navigate to authors list page if user not logged in
                }
            }

            if (!IsPostBack)
            {
                populateProfileDetailsView();
                populateCollaborationsStartedGridView();
                //populateCollaborationsJoinedRepeater();
            }

            // hide stuff
            if (functions.getDataFromTable("SELECT TOP 1 ID FROM eBookAuthorView WHERE profileUserName = @f1", Request.Params["profileUserName"])[0] == "") // do this if user has not uploaded any ebooks
            {
                publishedEBooksPlaceHolder.Visible = false;
            }
            if (functions.getDataFromTable("SELECT TOP 1 ID FROM collaborationRequests WHERE originalPoster = @f1", Request.Params["profileUserName"])[0] == "") // do this if user has not started any collaborations
            {
                collaborationsStartedPlaceHolder.Visible = false;
            }
            if (functions.getDataFromTable("SELECT TOP 1 ID FROM userCollaborationsView WHERE profileUserName = @f1 AND state = 'requestAccepted'", Request.Params["profileUserName"])[0] == "") // do this if user has not joined any collaborations
            {
                collaborationsJoinedPlaceHolder.Visible = false;
            }

            if (!User.Identity.IsAuthenticated)
            {
                collaborationsStartedPlaceHolder.Visible = false;
                collaborationsJoinedPlaceHolder.Visible = false;
            }
            else if (User.IsInRole("subscribers"))
            {
                collaborationsStartedPlaceHolder.Visible = false;
                collaborationsJoinedPlaceHolder.Visible = false;
            }
            if (Request.Params["profileUserName"] != User.Identity.Name)
            {
                btnEditProfile.Visible = false;
            }
        }

        //private void hideFromPublicView()
        //{
        //    hideFromSubscribers(); // add these objects to list of things to hide too

            // List of objects to hide from public view
        //}

        //private void hideFromSubscribers()
        //{
        //    hideFromOtherAuthenticatedUsers(); // add these objects to list of things to hide too

            // List of objects to hide from logged in subscribers
            
        //}

        //private void hideFromOtherAuthenticatedUsers()
        //{
            // List of objects to hide from other logged in users above subscriber role level
            
            
        //}

        protected void collaborationsStartedGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // check row is data row (not header or footer)
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // get collaboration request post ID from row using datakeys
                string postId = collaborationsStartedGridView.DataKeys[e.Row.RowIndex].Values[0].ToString();

                // populate nested requested collaborators repeater on logged-in user's profile, else hide from other users and show send request to collaborate button instead
                var rptImage1 = e.Row.FindControl("requestedCollaboratorsRepeater") as Repeater;
                if (rptImage1 != null)
                {
                    if (Request.Params["profileUserName"] == User.Identity.Name) // do this if logged in user on own profile page
                    {
                        functions.fillRepeater(rptImage1, "SELECT [ID], [originalPoster], [FirstName], [LastName], [profileUserName], [state] FROM [userCollaborationsView] WHERE (([ID] = " + postId + ") AND ([originalPoster] = @f1) AND ([state] = 'requestSent')) ORDER BY [LastName], [FirstName]", Request.Params["profileUserName"]);
                        e.Row.FindControl("btnSendCollaboratorRequest").Visible = false; // hide send collaborator request button
                        e.Row.FindControl("btnCollaboratorRequestSent").Visible = false; // hide collaborator request sent button
                    }
                    else // do this if logged in user on another user's profile page
                    {
                        e.Row.FindControl("requestedCollaboratorsRepeater").Visible = false; // hide requested collaborators repeater as stated above

                        if (functions.getDataFromTable("SELECT [state] FROM [userCollaborationsView] WHERE (([ID] = " + postId + ") AND ([profileUserName] = @f1))", User.Identity.Name)[0] == "")
                        {
                            e.Row.FindControl("btnCollaboratorRequestSent").Visible = false; // hide request sent button if user has not sent a request to collaborate on post
                        }
                        else
                        {
                            e.Row.FindControl("btnSendCollaboratorRequest").Visible = false; // else hide send request button if they have already sent a request to collaborate
                        }
                    }
                }

                // populate nested accepted collaborators repeater
                var rptImage2 = e.Row.FindControl("acceptedCollaboratorsRepeater") as Repeater;
                if (rptImage2 != null)
                {
                    functions.fillRepeater(rptImage2, "SELECT [ID], [originalPoster], [FirstName], [LastName], [profileUserName], [state] FROM [userCollaborationsView] WHERE (([ID] = " + postId + ") AND ([originalPoster] = @f1) AND ([state] = 'requestAccepted')) ORDER BY [LastName], [FirstName]", User.Identity.Name);
                }
            }
        }

        //private void populateCollaborationRequestsListView()
        //{
        //    functions.fillDataView(collaborationRequestsListView, "SELECT collaborationRequests.ID, collaborationRequests.description, collaborationRequests.dateOfPost, collaborationRequests.originalPoster, profile.FirstName, profile.LastName, profile.profileUserName FROM collaborationRequests, profile WHERE collaborationRequests.originalPoster = profile.profileUserName ORDER BY [collaborationRequests.ID] DESC", null);
        //

        protected void btnAcceptCollaboratorRequest_Click(object sender, EventArgs e)
        {
            string[] cmdArguments = ((Button)sender).CommandArgument.Split(';');
            string postId = cmdArguments[0];
            string userName = cmdArguments[1];
            object[] parameters = { "requestAccepted", postId, functions.getDataFromTable("SELECT ID FROM profile WHERE profileUserName = @f1", userName)[0] };
            functions.putDataInTable("UPDATE userCollaborationJunction SET state = @f1 WHERE collaboration_fkid = @f2 AND user_fkid = @f3", parameters);
            populateCollaborationsStartedGridView();
        }
        
        protected void btnSendCollaboratorRequest_Click(object sender, EventArgs e)
        {
            string postId = ((Button)sender).CommandArgument;
            insertCollaborationRequestCollaboratorFkidsIntoJunctionTable(postId);
            populateCollaborationsStartedGridView();
            //populateCollaborationRequestsListView();
            //var item = (ListViewItem)btn.NamingContainer;
            //int index = item.DisplayIndex;
            //collaborationRequestsListView.
            //int id = (int)collaborationRequestsListView.DataKeys[itemIndex]["ID"];
        }

        private void insertCollaborationRequestCollaboratorFkidsIntoJunctionTable(string postId)
        {
            object[] parameters = { functions.getDataFromTable("SELECT ID FROM profile WHERE profileUserName = @f1", User.Identity.Name)[0], postId, "requestSent" };
            functions.putDataInTable("INSERT INTO userCollaborationJunction(user_fkid,collaboration_fkid,state) VALUES(@f1,@f2,@f3)", parameters);
        }

        private void populateProfileDetailsView()
        {
            functions.fillDataView(profileDetailsView, "SELECT * FROM profile WHERE profileUserName = @f1", Request.Params["profileUserName"]);
        }

        private void populateCollaborationsStartedGridView()
        {
            functions.fillDataView(collaborationsStartedGridView, "SELECT [ID], [description], [dateOfPost], [originalPoster] FROM [collaborationRequests] WHERE ([originalPoster] = @f1) ORDER BY [ID] DESC", Request.Params["profileUserName"]);
        }

        protected void collaborationsJoinedGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            // check row is data row (not header or footer)
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // get post ID from row using datakeys
                string postId = collaborationsJoinedGridView.DataKeys[e.Row.RowIndex].Values[0].ToString();

                // populate nested collaborators repeater on profile
                var rptImage = e.Row.FindControl("collaboratorsJoinedRepeater") as Repeater;
                if (rptImage != null)
                {
                    functions.fillRepeater(rptImage, "SELECT [ID], [FirstName], [LastName], [profileUserName], [state] FROM [userCollaborationsView] WHERE (([ID] = @f1) AND ([state] = 'requestAccepted')) ORDER BY [ID] DESC", postId);
                }
            }
        }
    }
}